<template>
  <div class="dashboard-container">
    <el-card class="tree-card">
      <!-- 用了一个行列布局 -->
      <TreeTools :tree-node="company" :is-root="true" @adddepartment="adddepartment" />
      <el-tree :data="departs" :expand-on-click-node="false" :default-expand-all="true">
        <template #default="{data}">
          <TreeTools

            :tree-node="data"
            :is-root="false"
            @eidtdepartment="eidtDepartment"
            @deldepartment="delDepartment"
            @adddepartment="adddepartment"
          />
        </template>

      </el-tree>
      <adddept ref="adddept" :show-dialog.sync="showDialog" :node="node" @addDepartment="delDepartment" />
      <!-- //  default-expand-all是否默认展开所有节点	 -->
      <!-- //  :expand-on-click-node是否在点击节点的时候展开或者收缩节点， 默认值为 true，如果为 false，则只有点箭头图标的时候才会展开或者收缩节点。	 -->

    </el-card>
  </div>
</template>

<script>
// import { mapGetters } from 'vuex'
import TreeTools from '@/views/departments/components/tree-tools.vue'
import adddept from '@/views/departments/components/add-dept.vue'
import { department } from '@/api/department.js'
export default {
  components: {
    TreeTools,
    adddept
  },

  data() {
    return {
      node: {},
      showDialog: false,
      company: { name: '江苏传智播客教育科技股份有限公司 ', manager: '负责人' },
      departs: [],
      defaultProps: {
        label: 'name' // 把原来的label改成name
      }
    }
  },
  created() {
    this.delDepartment()
  },
  methods: {
    adddepartment(node) {
      this.node = node
      // console.log(this.node)
      this.showDialog = true
    },
    eidtDepartment(node) {
      this.showDialog = true
      this.$refs.adddept.eidtdepartment(node)
    },
    async delDepartment() {
      const { depts } = await department()
      this.departs = this.digui(depts, '')
    },
    // 递归算法
    // digui(depts, pid) {
    //   const res = []
    //   depts.forEach((ele) => {
    //     if (ele.pid === pid) {
    //       ele.children = this.digui(depts, ele.id)
    //       res.push(ele)
    //     }
    //   })
    //   return res
    // }
    // 非递归算法
    digui(list, topPid) {
      list.forEach((ele) => {
        if (ele.pid !== topPid) {
          const parent = list.find((el) => el.id === ele.pid)
          if (parent) {
            parent.children = parent.children || []
            parent.children.push(ele)
          }
        }
      })
      return list.filter((ele) => ele.pid === topPid)
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
.tree-card {
  padding: 30px  140px;
  font-size:14px;
}
</style>
